package edcom.client;

import org.apache.tools.ant.types.Assertions.EnabledAssertion;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.BlurEvent;
import com.google.gwt.event.dom.client.BlurHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.FocusEvent;
import com.google.gwt.event.dom.client.FocusHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.*;
import com.google.gwt.user.client.ui.HasHorizontalAlignment.HorizontalAlignmentConstant;
import com.google.gwt.user.client.ui.ValueBoxBase.TextAlignment;

@SuppressWarnings("unused")
public class LogBox {

	RootPanel logSpace = null;

	private LoginRequestServiceAsync loginSVC = GWT.create(LoginRequestService.class); 
	private FlexTable flexTableLogin;
	private FlexTable flexTableLogout;
	private FlexTable container;
	private PasswordTextBox textBoxPassword;
	private TextBox textBoxUsername;
	private TextBox usernameMask;
	private TextBox passwordMask;
	private TextBox textBoxTag;
	private Button buttonLogin;
	private Button buttonLogOut;
	private Label lblYouAreLogged;

	public LogBox() {
		/*
		 * DO NOT INSTANTIATE THIS WAY
		 */
	}

	public LogBox(RootPanel logBox) {

		if(logBox == null) {
//			throw new NullPointerException("must be instantiated with a " +
//			"valid root panel");
		}
		else{
			logSpace = logBox;
			
			if(!Cookies.isCookieEnabled()) {
				logSpace.add(new HTML("<br/>Please enable your <br/>browser's " +
				"cookies so <br/>you can use <br/>the site's services."));
			} else {

				/*
				 * check the cookies
				 */
				String username = Cookies.getCookie("username");
				if(username != null) {
					buildLogout(username);
				} else {
					buildLogin();
				}
			}
		}
	}

	protected void hidePasswordMask() {
		flexTableLogin.setWidget(1, 0, textBoxPassword);
	}

	protected void hideUsernameMask() {
		flexTableLogin.setWidget(0, 0, textBoxUsername);
	}

	public void buildLogin() {
		logSpace.clear();
		
		flexTableLogin = new FlexTable();
		flexTableLogin.setWidth("180px");

		textBoxUsername = new TextBox();
		textBoxUsername.setVisibleLength(20);
		textBoxUsername.setMaxLength(20);
		textBoxUsername.setStyleName("gwt-TextBoxEnabled");
		textBoxUsername.addBlurHandler(new BlurHandler() {
			@Override
			public void onBlur(BlurEvent event) {
				if(textBoxUsername.getText().trim().isEmpty()) {
					showUsernameMask();
				}
			}
		});
		textBoxUsername.addKeyPressHandler(new KeyPressHandler() {
			public void onKeyPress(KeyPressEvent event) {
				if(event.getCharCode() == KeyCodes.KEY_ENTER) {
					passwordMask.setFocus(true);
				}
			}
		});
		

		textBoxPassword = new PasswordTextBox();
		textBoxPassword.setVisibleLength(20);
		textBoxPassword.setMaxLength(16);
		textBoxPassword.setStyleName("gwt-TextBoxEnabled");
		textBoxPassword.addBlurHandler(new BlurHandler() {
			@Override
			public void onBlur(BlurEvent event) {
				if(textBoxPassword.getText().trim().isEmpty()) {
					showPasswordMask();
				}
			}
		});
		textBoxPassword.addKeyPressHandler(new KeyPressHandler() {
			public void onKeyPress(KeyPressEvent event) {
				if(event.getCharCode() == KeyCodes.KEY_ENTER) {
					requestLogin(textBoxUsername.getText(), textBoxPassword.getText());
				}
			}
		});

		buttonLogin = new Button("Login");
		buttonLogin.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				requestLogin(textBoxUsername.getText(), textBoxPassword.getText());
			}
		});
		buttonLogin.setStyleName("gwt-ButtonLogin");
		flexTableLogin.setWidget(2, 0, buttonLogin);

		flexTableLogin.getCellFormatter().setHorizontalAlignment(0, 0, HasHorizontalAlignment.ALIGN_CENTER);
		flexTableLogin.getCellFormatter().setHorizontalAlignment(1, 0, HasHorizontalAlignment.ALIGN_CENTER);
		flexTableLogin.getCellFormatter().setHorizontalAlignment(2, 0, HasHorizontalAlignment.ALIGN_CENTER);

		usernameMask = new TextBox();
		usernameMask.setText("Username");				
		usernameMask.setVisibleLength(20);
		usernameMask.setReadOnly(true);
		usernameMask.setStyleName("gwt-TextBoxDisabled");
		usernameMask.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				hideUsernameMask();
				textBoxUsername.setFocus(true);
			}
		});
		usernameMask.addFocusHandler(new FocusHandler() {
			@Override
			public void onFocus(FocusEvent event) {
				hideUsernameMask();
				textBoxUsername.setFocus(true);
			}
		});

		passwordMask = new TextBox();
		passwordMask.setText("Password");
		passwordMask.setVisibleLength(20);
		passwordMask.setReadOnly(true);
		passwordMask.setStyleName("gwt-TextBoxDisabled");
		passwordMask.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				hidePasswordMask();
				textBoxPassword.setFocus(true);
			}
		});
		passwordMask.addFocusHandler(new FocusHandler() {
			@Override
			public void onFocus(FocusEvent event) {
				hidePasswordMask();
				textBoxPassword.setFocus(true);
			}
		});
		
		logSpace.add(flexTableLogin);
		showUsernameMask();
		showPasswordMask();
	}

	protected void showUsernameMask() {
		flexTableLogin.setWidget(0, 0, usernameMask);
	}

	private void showPasswordMask() {
		flexTableLogin.setWidget(1, 0, passwordMask);
	}

	public void buildLogout(String username) {
		logSpace.clear();
		
		flexTableLogout = new FlexTable();
		flexTableLogout.setWidth("180px");

		lblYouAreLogged = new Label("You are logged in as:");
		flexTableLogout.setWidget(0, 0, lblYouAreLogged);
//		lblYouAreLogged.setWidth("180px");

		buttonLogOut = new Button("New button");
		buttonLogOut.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				/*
				 * just remove the cookies and reset the panel
				 */
				Cookies.removeCookie("usertype");
				Cookies.removeCookie("username");
//				logSpace.clear();
//				buildLogin();
				Window.Location.reload();
			}
		});

		textBoxTag = new TextBox();
		textBoxTag.setEnabled(false);
		textBoxTag.setVisibleLength(15);
		textBoxTag.setAlignment(TextAlignment.CENTER);
		flexTableLogout.setWidget(1, 0, textBoxTag);

		buttonLogOut.setText("Log out");
		buttonLogOut.setStyleName("gwt-ButtonEXT");
		flexTableLogout.setWidget(2, 0, buttonLogOut);

		flexTableLogout.getCellFormatter().setVerticalAlignment(2, 0, HasVerticalAlignment.ALIGN_BOTTOM);
		flexTableLogout.getCellFormatter().setHorizontalAlignment(2, 0, HasHorizontalAlignment.ALIGN_CENTER);
		flexTableLogout.getCellFormatter().setHorizontalAlignment(1, 0, HasHorizontalAlignment.ALIGN_CENTER);
		flexTableLogout.getCellFormatter().setHorizontalAlignment(0, 0, HasHorizontalAlignment.ALIGN_CENTER);
		
		logSpace.add(flexTableLogout);
		textBoxTag.setText(username);
	}

	protected void requestLogin(String username, String password) {
		AsyncCallback<String[]> callback = new AsyncCallback<String[]>() {

			public void onFailure(Throwable caught) {
				Window.alert("The server was unable to process your " +
				"request.\nPlease try again later.");
			}

			public void onSuccess(String[] result) {
				if(!result[Student.sqlStatus].isEmpty() || 
						!result[Student.generalError].isEmpty()) {
					Window.alert("Wrong username or password!");
				} else {
					if(result[Student.username].equals("edcenteno") || 
							result[Student.username].equals("sysadmin")) {
						Cookies.setCookie("usertype", "admin", null, null, "/", false);
					} else {
						Cookies.setCookie("usertype", "user", null, null, "/", false);
					}
					Cookies.setCookie("username", result[Student.username], null, null, "/", false);
//					logSpace.clear();
//					buildLogout(result[Student.username]);
					Window.Location.reload();
				}
			}
		};

		loginSVC.requestLogin(username, password, callback);
	}

}
